import { defineStore } from 'pinia'
import { ServiceWebSocket } from '../utils/websocket'

export const useWebSocketStore = defineStore('websocket', {
  state: () => ({
    ws: null,
    serviceId: '1001',
    isConnected: false,
    userList: [],
    unreadCounts: {},
    messageHandlers: new Map(), // 存储不同页面的消息处理器
    userConnectedHandlers: [] // 存储用户连接的回调函数
  }),

  actions: {
    /**
     * 初始化 WebSocket 连接
     */
    init() {
      // 如果已经存在连接且已连接，直接返回
      if (this.ws && this.ws.isConnected()) {
        console.log('WebSocket 已连接，无需重复初始化')
        return
      }
      
      // 如果存在连接但未连接，先断开
      if (this.ws) {
        console.log('检测到未连接的 WebSocket，先断开')
        this.ws.disconnect()
        this.ws = null
      }

      this.ws = new ServiceWebSocket(this.serviceId)

      // 用户连接回调
      this.ws.onUserConnected = (userData) => {
        const existingUser = this.userList.find(u => u.userId === userData.userid)
        if (!existingUser) {
          this.userList.push({
            userId: userData.userid,
            name: userData.name,
            connectedAt: new Date()
          })
          
          // 触发所有注册的用户连接回调
          this.userConnectedHandlers.forEach((handler) => {
            if (typeof handler === 'function') {
              handler(userData)
            }
          })
        }
      }

      // 消息回调 - 分发给所有注册的处理器
      this.ws.onMessage = (messageData) => {
        // 如果是发给客服的消息，增加未读数
        if (messageData.from && messageData.to === `service${this.serviceId}`) {
          const fromUserId = messageData.from
          if (!this.unreadCounts[fromUserId]) {
            this.unreadCounts[fromUserId] = 0
          }
          this.unreadCounts[fromUserId]++
        }

        // 分发给所有注册的处理器
        this.messageHandlers.forEach((handler) => {
          if (typeof handler === 'function') {
            handler(messageData)
          }
        })
      }

      // 错误回调
      this.ws.onError = (error) => {
        console.error('WebSocket 错误:', error)
        this.isConnected = false
      }

      // 关闭回调
      this.ws.onClose = () => {
        this.isConnected = false
      }

      this.ws.connect()

      // 检查连接状态
      const checkInterval = setInterval(() => {
        if (this.ws && this.ws.isConnected()) {
          this.isConnected = true
          clearInterval(checkInterval)
        }
      }, 100)
    },

    /**
     * 注册消息处理器
     */
    registerMessageHandler(key, handler) {
      this.messageHandlers.set(key, handler)
    },

    /**
     * 移除消息处理器
     */
    unregisterMessageHandler(key) {
      this.messageHandlers.delete(key)
    },

    /**
     * 注册用户连接回调
     */
    registerUserConnectedHandler(handler) {
      this.userConnectedHandlers.push(handler)
    },

    /**
     * 移除用户连接回调
     */
    unregisterUserConnectedHandler(handler) {
      const index = this.userConnectedHandlers.indexOf(handler)
      if (index > -1) {
        this.userConnectedHandlers.splice(index, 1)
      }
    },

    /**
     * 发送消息
     */
    sendMessage(toUserId, message, extraData = {}) {
      if (!this.ws || !this.ws.isConnected()) {
        return false
      }
      return this.ws.sendMessage(toUserId, message, extraData)
    },

    /**
     * 清除未读数
     */
    clearUnreadCount(userId) {
      this.unreadCounts[userId] = 0
    },

    /**
     * 获取未读数
     */
    getUnreadCount(userId) {
      return this.unreadCounts[userId] || 0
    },

    /**
     * 断开连接
     */
    disconnect() {
      if (this.ws) {
        this.ws.disconnect()
        this.ws = null
      }
      this.isConnected = false
      this.userList = []
      this.unreadCounts = {}
      this.messageHandlers.clear()
    }
  }
})

